package com.examination.to.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.to.entity.User;
import com.examination.to.mapper.UserMapper;
import com.examination.to.service.UserService;
import com.examination.to.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * auther:FC
 * date:2021/5/10
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{


    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param user 参数封装
     * @return Result
     */
    @Override
    public Result register(User user) {

        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try {
            User existUser = userMapper.findByUsername(user.getUsername());
            if (existUser != null){
                //如果用户名已经存在
                result.setCode(-1);
                result.setMsg("用户名已经存在");
            }else {
                userMapper.register(user);
                result.setMsg("注册成功");
                result.setCode(200);
                result.setDetail(user);
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 登陆
     *
     * @param user 用户名和密码
     * @return Result
     */
    @Override
    public Result login(User user) {

        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try {
            User user1 = userMapper.login(user);
            if (user1 == null){
                result.setCode(-1);
                result.setMsg("用户名或者密码错误");
            }else {
                result.setCode(200);
                result.setMsg("登陆成功");
                result.setDetail(user);
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
